package com.dianrui.moonfire.push;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.dianrui.moonfire.R;
import com.dianrui.moonfire.activity.MessageDeatilsActivity;
import com.dianrui.moonfire.activity.PaySuccessActivity;
import com.dianrui.moonfire.activity.RidingPriceActivity;
import com.dianrui.moonfire.event.OpenOrClose;
import com.dianrui.moonfire.util.EventBusConstants;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * <p>
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 * @author lzy
 */
@SuppressWarnings("ALL")
public class ReceivedMessage extends BroadcastReceiver {
    private static final String TAG = "ReceivedMessage";

    @Override
    public void onReceive(final Context context, Intent intent) {

        try {
            Bundle bundle = intent.getExtras();
            Log.e(TAG, intent.getAction() + "\n[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

            Log.e(TAG, bundle.getString(JPushInterface.EXTRA_EXTRA));
            if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
                //接收到推送下来的通知
                Log.e(TAG, "[MyReceiver] 接收到推送下来的通知");
                if (bundle != null) {
                    String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);

                    if (!ExampleUtil.isEmpty(extras)) {
                        try {
                            JSONObject extraJson = new JSONObject(extras);
                            extras = extraJson.toString();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    if (!ExampleUtil.isEmpty(extras)) {
                        try {
                            JSONObject extraJson = new JSONObject(extras);
                            extras = extraJson.toString();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    final JSONObject orderJson = new JSONObject(extras);
                    switch (orderJson.optString("type")) {
                        /**后台发送消息**/
                        case "system":
                            EventBus.getDefault().post(EventBusConstants.REFRESH_MSG_LIST);
                            EventBus.getDefault().post(EventBusConstants.REFRESH_UNREAD_MSG);
                            break;
                        /**后台帮你还车**/
                        case "order":
                            pushEndCar(context, orderJson);
                            break;
                        /**后台踢人**/
                        case "login_out":
                            pushLoginOut(context);
                            break;
                        /**后台帮你付款**/
                        case "paymentSuccess":
                            EventBus.getDefault().post(new OpenOrClose(false));
                            EventBus.getDefault().post(EventBusConstants.PAYSUCCESSRFRESHLOCATION);
                            context.startActivity(new Intent(context, PaySuccessActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP));
                            break;

                            default:
                                break;


                    }
                }
            } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
                Log.e(TAG, "[MyReceiver] 用户点击打开了通知");
                String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
                if (!ExampleUtil.isEmpty(extras)) {
                    try {
                        JSONObject extraJson = new JSONObject(extras);
                        extras = extraJson.toString();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                if (!ExampleUtil.isEmpty(extras)) {
                    try {
                        JSONObject extraJson = new JSONObject(extras);
                        extras = extraJson.toString();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                final JSONObject orderJson = new JSONObject(extras);
                if ("system".equals(orderJson.optString("type"))) {
                    Intent intent1=new Intent(context, MessageDeatilsActivity.class);
                    Bundle bundle1=new Bundle();
                    bundle1.putString("id", orderJson.optString("ids"));
                    intent.putExtras(bundle);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**后台推送踢人**/
   private void pushLoginOut(final Context context) {
       EventBus.getDefault().post(EventBusConstants.LOGIN_OUT);

    }

    /**后台还车**/
   public void pushEndCar(Context context, JSONObject orderJson) {
       EventBus.getDefault().post(EventBusConstants.PAYMENT_STATUS);
       MediaPlayer mediaPlayer1 = MediaPlayer.create(context, R.raw.returncar);
       mediaPlayer1.start();
       Intent intent2 = new Intent(context, RidingPriceActivity.class);
       Bundle bundle=new Bundle();
       bundle.putString("id", orderJson.optString("ids"));
       intent2.putExtras(bundle);
        intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent2);
    }


    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {

                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next().toString();
                        sb.append("\nkey:" + key + ", value: [" + myKey + " - " + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {

                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }
}
